import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./userStore";
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart";
export const useCartStore = defineStore(
  "cart",
  () => {
    const cartList = ref([]);
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token);

    const updateNewList = async () => {
      const res = await findNewCartListAPI();
      cartList.value = res.result;
    };
    const addCart = async (goods) => {
      const { skuId, count } = goods;
      if (isLogin.value) {
        await insertCartAPI({ skuId, count });
        updateNewList();
      } else {
        const hasItem = cartList.value.find((item) => goods.skuId === item.skuId);
        if (hasItem) {
          hasItem.count += goods.count;
        } else {
          cartList.value.push(goods);
        }
      }
    };

    const delCart = async (skuId) => {
      if (isLogin.value) {
        await delCartAPI([skuId]);
        updateNewList();
      } else {
        cartList.value = cartList.value.filter((item) => item.skuId !== skuId);
      }
      };
      
      const clearCart = () => {
        cartList.value=[]
    }

    const singleCheckChange = (skuId, selected) => {
      const item = cartList.value.find((item) => item.skuId === skuId);
      item.selected = selected;
    };

    const allCheckChange = (selected) => {
      cartList.value.forEach((item) => (item.selected = selected));
    };

    const allCount = computed(() => cartList.value.reduce((pre, cur) => pre + cur.count, 0));
    const allPrice = computed(() =>
      cartList.value.reduce((pre, cur) => pre + cur.count * cur.price, 0)
    );
    const isAllSelected = computed(() => cartList.value.every((item) => item.selected));

    const selectedCount = computed(() =>
      cartList.value.filter((item) => item.selected).reduce((pre, cur) => pre + cur.count, 0)
    );
    const selectedPrice = computed(() =>
      cartList.value
        .filter((item) => item.selected)
        .reduce((pre, cur) => pre + cur.count * cur.price, 0)
    );

    return {
      cartList,
      allCount,
      allPrice,
      isAllSelected,
      selectedCount,
      selectedPrice,
      addCart,
      delCart,
      singleCheckChange,
      allCheckChange,
        clearCart,
      updateNewList,
    };
  },
  { persist: true }
);
